import { CombinationStatus, HandicapStatus, Match, MatchStatus } from '@prisma/client';
import { MatchData } from './init-data';

// 1/1 根据比赛结果，获取胜平负结果
export function resolveMatchResult(score: string): MatchStatus {
  if (!score) return MatchStatus.NOT_STARTED;
  const [homeScore, awayScore] = score.split(':').map(Number);

  if (isNaN(homeScore) || isNaN(awayScore)) {
    return MatchStatus.NOT_STARTED;
  }

  if (homeScore === awayScore) {
    return MatchStatus.DRAW;
  } else if (homeScore > awayScore) {
    return MatchStatus.WINNING;
  } else {
    return MatchStatus.LOSING;
  }
}

// 1/2 根据比赛结果，获取让球结果
// 1/2 根据比赛结果，获取让球结果
export function resolveHandicapResult(score: string, handicap: number): HandicapStatus {
  if (!score) return HandicapStatus.NOT_STARTED;
  const [homeScore, awayScore] = score.split(':').map(Number);

  if (isNaN(homeScore) || isNaN(awayScore)) {
    return HandicapStatus.NOT_STARTED;
  }

  // 计算让球后的比分
  const adjustedHomeScore = homeScore + handicap;

  if (adjustedHomeScore === awayScore) {
    return HandicapStatus.HANDICAP_DRAW; // 让平
  } else if (adjustedHomeScore > awayScore) {
    return HandicapStatus.HANDICAP_WINNING; // 让胜
  } else {
    return HandicapStatus.HANDICAP_LOSING; // 让负
  }
}

// 2 根据组合结果，获取胜平负结果
export function resolveCombinationResult(
  combinationData: MatchData[],
  matches: { matchId: number; status: MatchStatus; fullScore: string | null }[],
): CombinationStatus {
  const isWin = true;
  for (const combination of combinationData) {
    const match = matches.find((item) => item.matchId == combination.matchId);
    console.log(match);
    if (!match) return CombinationStatus.NOT_STARTED;

    // if (match.status === MatchStatus.NOT_STARTED) return CombinationStatus.NOT_STARTED;
    // if (match.status === MatchStatus.LOSING) isWin = false;
    // if (match.status === MatchStatus.WINNING) isWin = true;
    // if (match.status === MatchStatus.DRAW) isWin = false;
  }
  const matchResults = matches.map((item) => item.status);

  // 1. 如果有任何比赛未开始，组合状态为未开始
  if (matchResults.some((status) => status === MatchStatus.NOT_STARTED)) {
    return CombinationStatus.NOT_STARTED;
  }

  // 2. 如果有任何比赛输了，整个组合就输了
  if (matchResults.some((status) => status === MatchStatus.LOSING)) {
    return CombinationStatus.LOSING;
  }

  // 3. 如果所有比赛都赢了，组合才赢
  if (matchResults.every((status) => status === MatchStatus.WINNING)) {
    return CombinationStatus.WINNING;
  }

  // 4. 如果所有比赛都平局，组合也输了（因为平局不算赢）
  if (matchResults.every((status) => status === MatchStatus.DRAW)) {
    return CombinationStatus.LOSING;
  }

  // 5. 其他情况（部分平局部分赢）也输了
  return CombinationStatus.LOSING;
}

// 3 获取当天免费的比赛场次
export function getFreeBaseCountArray(): string[] {
  const count = Number(process.env.FREE_BASE_COUNT) || 5;
  return Array.from({ length: count }, (_, index) => {
    return String(index + 1).padStart(3, '0');
  });
}
